<template>
  <div class="dept-page art-full-height">
    <!-- 搜索栏 -->
    <DeptSearch v-show="showSearchBar" v-model="searchForm" @search="handleSearch" @reset="handleReset" />

    <ElCard class="art-table-card" shadow="never" :style="{ 'margin-top': showSearchBar ? '12px' : '0' }">
      <!-- 表格头部 -->
      <ArtTableHeader v-model:columns="columnChecks" v-model:showSearchBar="showSearchBar" :loading="loading"
        @refresh="refreshData">
        <template #left>
          <ElSpace wrap>
            <ElButton v-auth="'add'" type="primary" @click="showDialog('add')" v-ripple>新增部门</ElButton>
          </ElSpace>
        </template>
      </ArtTableHeader>

      <!-- 表格 -->
      <ArtTable rowKey="id" :loading="loading" :data="data" :columns="columns" :pagination="pagination"
        @pagination:size-change="handleSizeChange" @pagination:current-change="handleCurrentChange" />

      <!-- 部门新增/编辑弹窗 -->
      <DeptDialog v-model:visible="dialogVisible" :type="dialogType" :editData="currentDeptData"
        @submit="handleDialogSubmit" />
    </ElCard>
  </div>
</template>

<script setup lang="ts">
import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
import { useTable } from '@/composables/useTable'
import { fetchDeptList, deleteDept, type DeptResponse } from '@/api/system/dept'
import DeptSearch from '@/views/system/dept/modules/dept-search.vue'
import DeptDialog from '@/views/system/dept/modules/dept-dialog.vue'

defineOptions({ name: 'Dept' })

const showSearchBar = ref(false)

// 搜索表单
const searchForm = ref<Record<string, any>>({
  dept_name: undefined,
  dept_code: undefined,
  status: undefined,
  keyword: undefined
})

const {
  data,
  columns,
  columnChecks,
  loading,
  pagination,
  refreshData,
  handleSizeChange,
  handleCurrentChange,
  searchParams,
  getData
} = useTable({
  core: {
    apiFn: fetchDeptList,
    apiParams: {
      current: 1,
      size: 20,
      ...searchForm.value
    },
    immediate: false, // 禁用自动加载，避免重复请求
    columnsFactory: () => [
      { prop: 'id', label: 'ID', width: 80, checked: false },
      { prop: 'dept_code', label: '编码' },
      { prop: 'dept_name', label: '名称' },
      { prop: 'descriptions', label: '描述', checked: false },
      {
        prop: 'status',
        label: '状态',
        formatter: (row) =>
          h(
            ElTag,
            { type: (row as DeptResponse).status ? 'success' : 'info', effect: 'plain', size: 'small' },
            () => ((row as DeptResponse).status ? '启用' : '禁用')
          )
      },
      { prop: 'parent_name', label: '上级部门' },
      { prop: 'manager_name', label: '主管' },
      { prop: 'create_time', label: '创建时间' },
      {
        prop: 'operation',
        label: '操作',
        width: 120,
        aglin: 'right',
        formatter: (row) =>
          h('div', [
            h(ArtButtonTable, {
              type: 'edit',
              onClick: () => showDialog('edit', row)
            }),
            h(ArtButtonTable, {
              type: 'delete',
              onClick: () => handleDelete(row)
            })
          ])
      }
    ]
  }
})

// 处理搜索与重置
const handleSearch = (params: Record<string, any>) => {
  const keys = ['dept_name', 'dept_code', 'status', 'keyword']
  const sp = searchParams as Record<string, any>
  keys.forEach((k) => {
    sp[k] = params[k] ?? undefined
  })
  searchParams.current = 1
  getData()
}

const handleReset = () => {
  const keys = ['dept_name', 'dept_code', 'status', 'keyword']
  const sp = searchParams as Record<string, any>
  keys.forEach((k) => delete sp[k])
  searchParams.current = 1
  getData()
}

// 弹窗相关
const dialogType = ref<'add' | 'edit'>('add')
const dialogVisible = ref(false)
const currentDeptData = ref<Partial<DeptResponse>>({})

const showDialog = (type: 'add' | 'edit', row?: DeptResponse) => {
  dialogType.value = type
  currentDeptData.value = row || {}
  nextTick(() => {
    dialogVisible.value = true
  })
}

const handleDialogSubmit = async () => {
  dialogVisible.value = false
  currentDeptData.value = {}
  refreshData()
}

// 删除
const handleDelete = async (row: DeptResponse) => {
  try {
    await ElMessageBox.confirm(`确定要删除该部门吗？`, '删除部门', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    if (!row?.id) {
      ElMessage.error('缺少部门ID，无法删除')
      return
    }

    await deleteDept(Number(row.id))
    ElMessage.success('删除成功')
    refreshData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

// 页面初始化
onMounted(() => {
  getData()
})
</script>

<style lang="scss" scoped></style>